package com.huaao.micropolice.root.controllers.system;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;
import com.huaao.micropolice.common.util.JsonUtil;
import com.huaao.micropolice.core.common.page.GridPage;
import com.huaao.micropolice.core.common.page.Page;
import com.huaao.micropolice.core.model.system.Dict;
import com.huaao.micropolice.core.service.system.DictService;
import com.huaao.micropolice.root.controllers.BaseController;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

@Controller
@RequestMapping("system/dict")
public class DictController extends BaseController{
	@Autowired
	private DictService dictService;
 
	@RequestMapping("index.do")
	public String index() {
		return "/system/dict/index";
	}

	@RequestMapping(value="queryDictType.do",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String queryDictType(String dictId) {
		if(StringUtils.isEmpty(dictId)){
			return "[]";
		}
		List<Dict> list = dictService.queryDictType(dictId);
		String result = JSONArray.fromObject(list).toString();
		return result;
	}

	@RequestMapping(value="queryDictLike.do",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String queryDictLike(String name,GridPage gridPage) {
		Page page = dictService.queryDictLike(name, gridPage);
		String result = JSONObject.fromObject(page).toString();
		return result;
	}
	 
	@RequestMapping("save.do")
	public ResponseEntity<String> save(Dict item) {
		if(StringUtils.isEmpty(item.getId())){
			dictService.save(item);
		}else{
			dictService.update(item);
		}
		return super.ajaxModel(JSON, JsonUtil.toJson(successMap()));
	}
	
	@RequestMapping("del.do")
	public ResponseEntity<String> del(String id) {
		dictService.del(id);
		return super.ajaxModel(JSON, JsonUtil.toJson(successMap()));
	}
	 
	@RequestMapping("dels.do")
	public ResponseEntity<String> dels(@RequestParam(value = "ids[]") String[] ids){
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			for(String id: ids){
				dictService.del(id);
			}
			map = successMap();
		} catch (Exception e) {
			map = failMap();
		}
		return super.ajaxModel(JSON, JsonUtil.toJson(map));
	}
}
